<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>读取文件夹及内容</title>
    <style>
        body {
            padding: 0;
            margin: 0;
        }

        .container {
            display: flex;
            width: 100%;
            height: 100vh;
            background: #171e4d;
        }

        .left {
            width: 250px;
            height: 100%;
            padding: 20px;
            box-sizing: border-box;
            background: #2c3e50;
            display: flex;
            justify-content: center;
        }

        .btn {
            width: 200px;
            height: 30px;
        }

        .content {
            color: #fff;
        }
    </style>
</head>
<body>
<div class="container">
    <div class="left">
        <button class="btn">打开文件夹</button>
        <div></div>
    </div>
    <div class="content"></div>

    <script>
        const btn = document.querySelector('.btn')
        const content = document.querySelector('.content')
        btn.onclick = async function () {
            // 打开文件夹
            const files = await showDirectoryPicker()
            await fileTree(files)
            // 读取文件夹内容
            const fileHandler = files.children[6]
            await readFile(fileHandler)
        }

        async function readFile(fileHandler) {
            const file = await fileHandler.getFile()
            const reader = new FileReader()
            reader.onload = function (e) {
                if (file.type === 'image/png') {
                    const img = document.createElement("img")
                    img.src = e.target.result
                    img.style.width = '400px'
                    content.appendChild(img)
                } else {
                    content.textContent = e.target.result
                }
            }
            if (file.type === 'image/png') {
                reader.readAsDataURL(file)
            } else {
                reader.readAsText(file)
            }
        }

        async function fileTree(files) {
            if (files.kind === 'file') {
                return;
            }
            // 读取文件夹内容
            // 这是获取的元组 异步迭代器
            // const entries = await files.entries()
            const values = await files.values()
            files.children = []
            for await (const value of values) {
                files.children.push(value)
                await fileTree(value)
            }
        }

    </script>
</div>
</body>
</html>